package com.gamelife.web.security.filter;

import com.gamelife.web.config.redis.RedisCache;
import com.gamelife.web.constant.Constants;
import com.gamelife.web.constant.ResponseEnum;
import com.gamelife.web.domain.LoginUser;
import com.gamelife.web.exception.BaseException;
import com.gamelife.web.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        // 获取userId
        Long userId = JwtUtils.getUserId(request);
        if(userId == null){
            chain.doFilter(request, response);
            return;
        }

        // redis中获取LoginUser
        LoginUser loginUser = (LoginUser)redisCache.getCacheObject(Constants.LOGIN_USER_KEY + userId);

        if(loginUser == null){ // token 过期
            throw new BaseException(ResponseEnum.TokenFailure);
        }

        // 存入security 上下文中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        log.info("jwt - loginUser = {}",loginUser.toString() );

        chain.doFilter(request, response);
    }
}
